
import { getDict } from '@/api/common'

import { ref } from 'vue'

//  缓存 所有的 dict
const store = ref({});

async function setStore(dictNameArr = []) {
  const dictObj = {
    names: [],
    arr: []
  }

  const promises = dictNameArr.reduce((obj, dictName) => {
    if (!store.value[dictName]) {
      obj.names.push(dictName)
      obj.arr.push(getDict(dictName))
    }

    return obj;
  }, dictObj)

  const dists = await Promise.all(promises.arr);

  promises.names.forEach((dictName, index) => {
    const _d = dists[index] || {};

    //  加工数据
    if (_d) {
      _d.forEach(item => {
        item.text = item.name;
        item.value = item.code;
      })
    }

    store.value[dictName] = _d;
  })
}

export default function useDict() {
  return [store, setStore]
}